package org.duoyi.striver.proxy.handler;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.duoyi.striver.model.impl.Sleeper;
import org.duoyi.striver.proxy.annotation.Delay;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DelayHandler implements InvocationHandler {

    private Object target;

    public DelayHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Delay delay = target.getClass().getMethod(method.getName(), method.getParameterTypes()).getDeclaredAnnotation(Delay.class);
        if (delay == null) {
            return method.invoke(target, args);
        }
        int min = (int) (delay.before() * 0.8);
        int max = (int) (delay.before() * 1.2);
        long before = RandomUtil.randomLong(min, max);
        log.debug("前置延时{}ms", before);
        Sleeper.sleep(before);
        Object result = method.invoke(target, args);
        long after = RandomUtil.randomLong(min, max);
        log.debug("后置延时{}ms", after);
        Sleeper.sleep(after);
        return result;
    }
}
